<template>
  <div class="rank-detail" v-loading="loading">
    <div class="rank-header" v-if="rankInfo">
      <div class="rank-cover">
        <img
          :src="rankInfo.picUrl || '/img/default_rank.png'"
          :alt="rankInfo.name"
          @error="handleImageError"
        />
      </div>
      <div class="rank-basic-info">
        <h1>{{ rankInfo.name }}</h1>
        <p class="rank-update-time">更新时间: {{ rankInfo.updateTime }}</p>
        <p class="rank-desc" v-if="rankInfo.description">{{ rankInfo.description }}</p>
        <el-button type="primary" @click="playAllSongs">播放全部</el-button>
      </div>
    </div>

    <div class="songs-section">
      <h2>排行榜</h2>
      <el-table
        :data="rankSongs"
        stripe
        style="width: 100%"
        @row-click="playSong"
      >
        <el-table-column prop="rank" label="#" width="80">
          <template #default="scope">
            <span
              class="rank-index"
              :class="{ top: scope.row.rank <= 3 }"
            >
              {{ scope.row.rank }}
            </span>
          </template>
        </el-table-column>

        <el-table-column prop="name" label="歌曲名" min-width="200">
          <template #default="scope">
            <span class="song-name">{{ scope.row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="singer" label="歌手" min-width="150" />

        <el-table-column prop="album" label="专辑" min-width="200" />

        <el-table-column prop="duration" label="时长" width="100">
          <template #default="scope">
            {{ formatDuration(scope.row.duration) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" icon="Play" circle @click.stop="playSong(scope.row)" />
            <el-button icon="Plus" circle @click.stop="addToPlaylist(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePlayerStore } from '@/store/player'
import { ElMessage } from 'element-plus'

export default {
  name: 'RankDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const playerStore = usePlayerStore()

    // 数据状态
    const rankInfo = ref(null)
    const rankSongs = ref([])
    const loading = ref(false)

    // 模拟获取排行榜详情（需要后端API支持）
    const fetchRankDetail = async () => {
      try {
        loading.value = true
        const rankId = route.params.id

        // 这里应该调用实际的API
        // 暂时使用模拟数据
        await new Promise(resolve => setTimeout(resolve, 500))

        // 模拟排行榜信息
        rankInfo.value = {
          id: rankId,
          name: `排行榜 ${rankId}`,
          updateTime: new Date().toLocaleDateString(),
          description: `这是排行榜 ${rankId} 的详细介绍。该排行榜根据播放量、收藏量等数据综合计算得出。`,
          picUrl: ''
        }

        // 模拟排行榜歌曲
        rankSongs.value = Array.from({ length: 50 }, (_, index) => ({
          rank: index + 1,
          id: parseInt(rankId) * 1000 + index + 1,
          name: `歌曲 ${index + 1}`,
          singer: `歌手 ${(index % 8) + 1}`,
          album: `专辑 ${(index % 5) + 1}`,
          duration: Math.floor(Math.random() * 300) + 100
        }))
      } catch (error) {
        ElMessage.error('获取排行榜详情失败: ' + error.message)
        router.push('/ranks')
      } finally {
        loading.value = false
      }
    }

    // 播放歌曲
    const playSong = (song) => {
      playerStore.setCurrentSong(song)
      ElMessage.success(`正在播放: ${song.name}`)
    }

    // 添加到播放列表
    const addToPlaylist = (song) => {
      playerStore.addToPlaylist(song)
      ElMessage.success(`已添加到播放列表: ${song.name}`)
    }

    // 播放全部歌曲
    const playAllSongs = () => {
      if (rankSongs.value.length > 0) {
        playerStore.setPlaylist(rankSongs.value)
        playerStore.setCurrentSong(rankSongs.value[0])
        ElMessage.success('已开始播放排行榜全部歌曲')
      } else {
        ElMessage.warning('该排行榜暂无歌曲')
      }
    }

    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0:00'
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }

    // 处理图片加载错误
    const handleImageError = (e) => {
      e.target.src = '/img/default_rank.png'
    }

    // 初始化加载
    onMounted(() => {
      fetchRankDetail()
    })

    return {
      rankInfo,
      rankSongs,
      loading,
      playSong,
      addToPlaylist,
      playAllSongs,
      formatDuration,
      handleImageError
    }
  }
}
</script>

<style scoped>
.rank-detail {
  padding: 20px;
}

.rank-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.rank-cover {
  width: 200px;
  height: 200px;
  overflow: hidden;
  flex-shrink: 0;
}

.rank-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.rank-basic-info {
  flex: 1;
}

.rank-basic-info h1 {
  margin: 0 0 15px 0;
  font-size: 32px;
  color: #333;
}

.rank-update-time {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 16px;
}

.rank-desc {
  margin: 15px 0;
  color: #666;
  line-height: 1.6;
}

.songs-section h2 {
  margin: 30px 0 20px 0;
  font-size: 24px;
  color: #333;
}

.rank-index {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.rank-index.top {
  color: #ff6b6b;
  font-weight: bold;
}

.song-name {
  font-weight: 500;
  cursor: pointer;
}

.song-name:hover {
  color: #409eff;
}
</style>
